﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Kaskelot.SP.Model.Contracts;
using Kaskelot.SP.Services;
using Stockholm.SOA.Kaskelot.WCF.DataContracts;
using Kaskelot.SP.Core;
using System.Linq;

namespace Kaskelot.SP.UI.CONTROLTEMPLATES.Kaskelot.SP.UI.Forms
{
	public partial class MaterielForm : BaseForm, IForm
	{
		public string Id { get; set; }
		public string ParentId { get; set; }

		public Materiel Current { get; set; }

		protected void Page_Load(object sender, EventArgs e)
		{
			using (ByggnadService svc = new ByggnadService())
			{
				try
				{
					Current = svc.GetMateriel(new Guid(Id));
				}
				catch (Exception ex)
				{
					Logger.LogError(this, LayerNames.Services, "MaterielForm.Page_Load", "Error getting materiel", ex);
				}

				if (Current == null)
					Current = new Materiel();
			}

			using (LookupService svc = new LookupService())
			{
				IList<MaterielTyp> materieltyper = new List<MaterielTyp>();
				var list = svc.GetPublicMaterielTypList();
				foreach (MaterielTyp mt in list)
				{
					materieltyper.Add(mt);
				}

				var mtId = Current.MaterielTypId.HasValue ? Current.MaterielTypId.Value.ToString() : null;

				if (mtId.IsGuid())
				{
					if (materieltyper.Where(mt => mt.Id.ToString() == mtId).Count() == 0)
					{
						using (AdminService aSvc = new AdminService())
						{
							materieltyper.Add(aSvc.GetMaterielTyp(new Guid(mtId)));
						}
					}
				}

				IList<ListItem> typer = new List<ListItem>();
				foreach (MaterielTyp mt in materieltyper)
				{
					typer.Add(new ListItem() { Text = mt.Beskrivning, Value = mt.Id.ToString() });
				}

				TypRepeater.DataSource = typer;
				TypRepeater.DataBind();
			}
		}

		public string IsChecked()
		{
			if (Current.MaterielTypId.HasValue || Current.Id == Guid.Empty)
				return String.Empty;
			else
				return "checked=\"checked\"";
		}

		public string GetBeskrivningAndClass()
		{
			if (Current.MaterielTypId.HasValue || Current.Id == Guid.Empty)
				return String.Empty;
			else
				return "value=\"" + Current.Beskrivning + "\" class=\"required\"";
		}

		public string GetBeskrivningVisibility()
		{
			if (Current.MaterielTypId.HasValue || Current.Id == Guid.Empty)
				return "style=\"display:none;\"";
			else
				return String.Empty;
		}

		public string GetTypVisibility()
		{
			if (Current.MaterielTypId.HasValue || Current.Id == Guid.Empty)
				return String.Empty;
			else
				return "style=\"display:none;\"";
		}
	}
}
